package com.bpc.cs.util;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;
import org.hibernate.service.ServiceRegistry;
import org.hibernate.service.ServiceRegistryBuilder;

/**
 * @author   phan_tp
 * @datetime Dec 10, 2012 : 5:57:42 PM
 */
public class HibernateUtil {
	private static SessionFactory sessionFactory;
	private static ServiceRegistry serviceRegistry;

	/**
	 * Initial SessionFactory in Hibernate 4
	 * This fragment code only execute ONE time when server start
	 * This sessionFactory will be used in all transaction of Hibernate
	 */
	static {
		try {
			Configuration config = new Configuration().configure();
			serviceRegistry = new ServiceRegistryBuilder().applySettings(config.getProperties()).buildServiceRegistry();
			sessionFactory = config.buildSessionFactory(serviceRegistry);
		} catch (HibernateException he) {
			System.err.println("Error creating SessionFactory: " + he);
			throw new ExceptionInInitializerError(he);
		}
	}

	/**
	 * Get SessionFactory
	 * @return SessionFactory
	 */
	public static SessionFactory getSessionFactory() {
        return sessionFactory;
    }

	/**
	 * Get current session
	 * @return Session
	 */
	public static Session getCurrentSession() {
		return sessionFactory.getCurrentSession();
	}
}
